/**
 * This program is free software but WITHOUT ANY WARRANTY OR CONDITIONS OF ANY KIND.
 *
 * Copyright (C) 2008-2012 www.pretty-tools.com
 */

const VK_ESCAPE = Components.interfaces.nsIDOMKeyEvent.DOM_VK_ESCAPE;

var gProgressMeter;
var images;
var destination;
var idx = 0;

function saveNextImage()
{
    try
    {
        while (idx < images.length && !images[idx])
            idx++;

        if (idx >= images.length)
        {
            window.close();
            return;
        }

        var imgSource = images[idx++];
        if (0 != imgSource.indexOf("javascript:"))
            yrprxHTMLContentHelper.saveImage(imgSource, wsshSaveImageHelper.getImageFileName(destination, imgSource), onSaveComplete);
        else
        {
            var urlResolver = null;
            eval(imgSource.replace("javascript:", "urlResolver="));
            imgSource = urlResolver;

            imgSource(function(url) {
                if (!url)
                    saveNextImage();
                else
                    yrprxHTMLContentHelper.saveImage(url, wsshSaveImageHelper.getImageFileName(destination, url), onSaveComplete);
            });
        }

    }
    catch(ex)
    {
        var logger = yrprxFactory.createLogger("SaveImagesProgressDialog.js");
        if (logger.enabled) logger.error("saveNextImage: Exception: " + ex);
    }
}

function onSaveComplete()
{
    try
    {
        gProgressMeter.value = 100 * idx / images.length;
        if (idx == images.length)
            window.close();
        else
            setTimeout(saveNextImage, 0);
    }
    catch(ex)
    {
        var logger = yrprxFactory.createLogger("SaveImagesProgressDialog.js");
        if (logger.enabled) logger.error("onSaveComplete: Exception: " + ex);
    }
}

function onLoad()
{
    try
    {
        if (!("arguments" in window) || !window.arguments.length)
            window.close();

        gProgressMeter = document.getElementById("progressmeter");

        images = window.arguments[0];
        destination = window.arguments[1];

        saveNextImage();
    }
    catch(ex)
    {
        var logger = yrprxFactory.createLogger("SaveImagesProgressDialog.js");
        if (logger.enabled) logger.error("onLoad: Exception: " + ex);
    }
}

function onKeyPress(event)
{
    try
    {
        if (VK_ESCAPE == event.keyCode)
            close();
    }
    catch(ex)
    {
        var logger = yrprxFactory.createLogger("SaveImagesProgressDialog.js");
        if (logger.enabled) logger.error("onKeyPress: Exception: " + ex);
    }
}
